<template>
  <div class="app-container">

    <!--搜索区-->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="角色名称" prop="loginName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="角色状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--功能区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="mutilrows.length!=1"
          @click="handleUpdate(mutilrows[0])"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete(null)"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区table-->
    <el-table v-loading="loading" :data="this.pageData.rows" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" prop="id" width="80" />
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip= "true" />
      <el-table-column label="权限字符串" prop="roleKey" :show-overflow-tooltip= "true" />
      <el-table-column label="显示顺序" prop="sorts" :show-overflow-tooltip= "true" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==1">停用</el-tag>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="修改人" prop="updateBy" :show-overflow-tooltip= "true"/>

      <el-table-column label="修改时间" align="center" prop="updateTime" width="200" />

      <el-table-column label="备注" prop="remark" :show-overflow-tooltip= "true" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template v-if="scope.row.roleKey!='admin'" slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
<!--          <el-popover-->
<!--            v-if="scope.row.status==0"-->
<!--            placement="bottom-end"-->
<!--            width="150"-->
<!--            trigger="hover">-->

<!--            <el-button-group>-->
<!--              <el-link type="info" icon="el-icon-s-help">数据权限</el-link>-->
<!--              <el-link type="info" icon="el-icon-user-solid" underline="false">-->
<!--                <router-link to="./children/userRole">-->
<!--                  分配用户-->
<!--                </router-link>-->
<!--              </el-link>-->
<!--            </el-button-group>-->
<!--            <el-button type="text" slot="reference" size="mini">>>更多</el-button>-->
<!--          </el-popover>-->
        </template>
      </el-table-column>

    </el-table>

    <!--分页条 -->
    <div style="margin-top: 10px;">
      <el-pagination
        v-if="pageData.total>0"
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 30, 40,50,100]"
        :page-size="queryParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>




   <!--    单修and单增的弹窗-->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false"  >
        <el-form ref="form" :model="this.form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入分类名称(唯一)" />
          </el-form-item>
          <el-form-item label="权限字符串" prop="roleKey">
            <el-input v-model="form.roleKey" placeholder="请输入权限字符串" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="sorts">
            <el-input-number v-model="form.sorts" controls-position="right" :min="1" :max="10"/>
          </el-form-item>
          <el-form-item label="角色状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="item in statusList" :label="item.dictValue">{{item.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="权限分配" prop="status">
            <el-checkbox label="展开/折叠" v-model="menuExpand"   @change="changeExpandAll"></el-checkbox>
            <el-checkbox label="全选/全不选" v-model="menuNodeAll" @change="checkedTreeNodeAll"></el-checkbox>
            <el-checkbox label="父子联动" v-model="menuCheckStrictly" @change="checkedTreeConnect"></el-checkbox>
            <el-tree
              :data="menuTreeData"
              show-checkbox
              empty-text="无权限菜单"
              node-key="id"
              ref="tree"
              highlight-current
              class="mytree"
              :check-strictly="!menuCheckStrictly"
              :props="defaultProps">
            </el-tree>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="open=false">取 消</el-button>
          <el-button type="primary" :loading="isLoading" @click="submitFrom">确 定</el-button>
        </div>
      </el-dialog>


  </div>
</template>

<script>
import {getList, deletes, add,update, findById, existsRoleName, existsRoleKey} from '@/api/system/role.js'
import { getRoleMenuTree} from '@/api/system/menu.js'
import {getDictTypeList} from '@/api/system/dictData.js'
import pageMixin from '@/utils/pageMixiny'
import addOrEditMixin from '@/utils/addOrEditMixin.js'

export default {
  name: 'Role',
  mixins: [pageMixin,addOrEditMixin],
  data() {
    //检查角色名称是否存在
    var isExistsRoleName = (rule, value, callback) => {
      existsRoleName({id: this.form.id, roleName:value}).then((response)=>{
        if (response){
          callback(new Error())
        }else {
          callback()
        }
      })
    }
    //检查权限字符是否存在
    var isExistsRoleKey = (rule, value, callback) => {
      existsRoleKey({id: this.form.id, roleKey:value}).then((response)=>{
        if (response){
          callback(new Error())
        }else {
          callback()
        }
      })
    }
    return {
      queryParams: {
        roleName: null,
        status: null
      },
      statusList: [],
      //表单验证规则
      rules: {
        roleName: [
          { required: true, message: '角色名称必须填写', trrigeer: 'blur' },
          { validator: isExistsRoleName, message: '该名称已被占用', trrigeer: 'blur' }
        ],
        roleKey: [
          { required: true, message: '权限字符必须填写', trrigeer: 'blur' },
          { validator: isExistsRoleKey, message: '该权限字符已被占用', trrigeer: 'blur' }
        ]
      },
      // 树的变量
      menuTreeData:[],
      // 数据解析属性(后台label和children，这个可以省略)
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isLoading: false,
      isDisabled: true,
      // 是否展开和折叠
      menuExpand: false,
      // 是否全选
      menuNodeAll: false,
      //父子联动
      menuCheckStrictly: true,

    }
  },
  created() {
    this.fetchDictDataByType()
    this.fetchMenuTree()
  },
  methods: {
    fetchDictDataByType(){
      getDictTypeList('sys_normal_disable').then(resp=> {
        this.statusList= resp
      })
    },
    //读取树型节点的值
    fetchMenuTree(){
      getRoleMenuTree().then(resp => {
        this.menuTreeData=resp
      })
    },
    //全选
    checkedTreeNodeAll(value) {
      if(this.$refs.tree){
         this.$refs.tree.setCheckedNodes(value ? this.menuTreeData: []);
      }
    },
    //展开/折叠
    changeExpandAll(value){
       // 展开第一级
        // let treeList = this.menuTreeData;
        // for (let i = 0; i < treeList.length; i++) {
        //   this.$refs.tree.store.nodesMap[treeList[i].id].expanded = value;
        // }
        //展开所有级
        if(this.$refs.tree){
          for(let i=0;i<this.$refs.tree.store._getAllNodes().length;i++){
             this.$refs.tree.store._getAllNodes()[i].expanded=value;
          }
        }
    },
    // 父子联动
    checkedTreeConnect(value){
      this.menuCheckStrictly = value;
    },
    // 角色查询
    fetchData() {
      this.loading = true
      getList(this.queryParams).then(response => {
        this.pageData = response
      }).finally(()=>{
        this.loading = false
      })
    },
    // 删除
    deleteOptions() {
      this.isDelete = true
      var ids = this.mutilrows.map(p => p.id)
      deletes(ids).then((res) => {
        this.fetchData()
      }).finally(() => {
        this.isDelete = false
        this.dialogVisible = false
      })
    },
    // 提交表单
    submitFrom() {
      this.isLoading = true
      //到得勾选菜单
      this.form.owernMenus=this.$refs.tree.getHalfCheckedKeys().concat(this.$refs.tree.getCheckedKeys())
      this.$refs.form.validate((status)=>{
        if (status){
          if (this.form.id){
            update(this.form).then((res)=>{
              this.fetchData()
            }).finally(()=>{
              this.isLoading=false
              this.open=false
            })
          }else {
            add(this.form).then(
              this.fetchData()
            ).finally(()=>{
              this.isLoading=false
              this.open=false;
            })
          }
        }else {
          this.isLoading=false
        }
      })
    },
    beforehandleDelete(ids) {
      deletes(ids).then((res) => {
        this.fetchData()
      }).finally(() => {
        this.isDelete = false
        this.dialogVisible = false
      })
    },
    beforeHandlerAdd() {
      this.form = {
        id: null,
        remark: null,
        roleKey: null,
        roleName: null,
        sorts: null,
        status: '0',
        owernMenus: []
      }
      // 清空清空所有的选项
      this.menuExpand=false
      this.checkedTreeNodeAll(this.menuExpand)
      // 菜单全部折叠起来
      this.menuNodeAll=false
      this.changeExpandAll(this.menuNodeAll)
      //父子联动
      this.menuCheckStrictly=true
      this.checkedTreeConnect(this.menuCheckStrictly)

    },
    beforeHandlerUpdate(id) {
      this.form = {
        name: null,
        picture: null,
        remark: null,
        roleKey: null,
        roleName: null,
        sorts: null,
        status: null,
        owernMenus: []
      }
      // 清空清空所有的选项
      this.menuExpand=false
      this.checkedTreeNodeAll(this.menuExpand)
      // 菜单全部折叠起来
      this.menuNodeAll=false
      this.changeExpandAll(this.menuNodeAll)
      //父子联动(不要)
      this.menuCheckStrictly=false
      this.checkedTreeConnect(this.menuCheckStrictly)
      this.open=true
      //查询数据
      findById(id).then( resp=> {
        this.form= resp
        // 还原菜单  更改数据后当你想立即使用js操作新的视图的时候需要使用它
        this.$nextTick(() => {
          console.log(this.$refs);

              this.$refs.tree.setCheckedKeys(this.form.owernMenus?this.form.owernMenus:[]);
              //父子联动(要)
              this.menuCheckStrictly=true
              this.checkedTreeConnect(this.menuCheckStrictly)

        })

      })

    },
    // 状态改变事件
    handleStatusChange(val) {

    }
  }
}


</script>

<style scoped>
.mytree{
  border: 1px solid #757575;
}

</style>
